/*
 * @(#)CheckRefererInterceptor.java $version 2011. 10. 14
 * 
 * Copyright 2011 NHN Corp. All rights Reserved.
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.hangame.mbl.interceptor.checkreferer;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nhncorp.hancore.action.AlertForward;
import com.nhncorp.lucy.common.data.DataHandlerFactory;
import com.opensymphony.webwork.WebWorkStatics;
import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.interceptor.Interceptor;

// TODO: Auto-generated Javadoc
/**
 * CSRFCheck CSRFCheckInterceptor 취약점 보강을 위한 Interceptor
 * 
 * The Class CheckRefererInterceptor.
 *
 * @author NHN
 */
@SuppressWarnings("serial")
public class CheckRefererInterceptor implements Interceptor, WebWorkStatics {

	/** The log. */
	private static Log log = LogFactory.getLog(CheckRefererInterceptor.class);

	/**
	 * destroy.
	 * 
	 * @see com.opensymphony.xwork.interceptor.Interceptor#destroy()
	 */
	public void destroy() {
	}

	/**
	 * init.
	 * 
	 * @see com.opensymphony.xwork.interceptor.Interceptor#init()
	 */
	public void init() {
	}

	/**
	 * intercept.
	 * 
	 * @param invocation ActionInvocation
	 * @return redirect or invoke
	 * @throws Exception Exception
	 * @see com.opensymphony.xwork.interceptor.Interceptor#intercept(com.opensymphony.xwork.ActionInvocation)
	 */
	public String intercept(ActionInvocation invocation) throws Exception {
		CheckReferer checkReferer = getAnnotation(invocation);

		if (checkReferer != null) {
			HttpServletRequest request = (HttpServletRequest)invocation.getInvocationContext().get(HTTP_REQUEST);
			String referer = StringUtils.defaultString(request.getHeader("referer"), "");
			log.debug("referer : " + referer);

			if (!CheckRefererHelper.validates(referer)) {
				return AlertForward.alertAndGoPage("error.refererNotFound", DataHandlerFactory.getDataHandler().get("url/smart") + "/index.nhn");
			}
		}

		return invocation.invoke();
	}

	/**
	 * Gets the annotation.
	 * 
	 * @param invocation ActionInvocation
	 * @return CheckReferer
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private CheckReferer getAnnotation(ActionInvocation invocation) {
		Class actionClazz = invocation.getAction().getClass();
		String methodName = invocation.getProxy().getMethod();
		CheckReferer checkReferer = null;
		try {
			Method method = actionClazz.getMethod(methodName, new Class[0]);
			checkReferer = method.getAnnotation(CheckReferer.class);
		} catch (SecurityException e) {
			log.debug(e);
		} catch (NoSuchMethodException e) {
			log.debug(e);
		}
		return checkReferer;
	}

}
